package MultiThread;

public class q1115_FooBar {
    private int n;
    private volatile int flag = 1;
    private final Object obj = new Object();
    /*
    如何交替的打印foo bar 并且一共是n次
    属于经典的交替执行任务方案
     */
    public q1115_FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (obj) {
                while (flag % 2 == 0) obj.wait();
                printFoo.run();
                flag++;
                obj.notifyAll();
            }
            // printFoo.run() outputs "foo". Do not change or remove this line.

        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            synchronized (obj) {
                while (flag % 2 != 0) obj.wait();
                printBar.run();
                flag++;
                obj.notifyAll();
            }
            // printBar.run() outputs "bar". Do not change or remove this line.

        }
    }
}
